#pragma once

#include <iostream>
#include <poll.h>
#include "Socket.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace socket_ns;

class PollServer
{
    // 总的文件描述符个数
    const static int gnum = sizeof(fd_set) * 8;
    const static int gdefaultfd = -1;

public:
    PollServer(uint16_t port)
        : _port(port), _listensocket(std::make_unique<TcpSocket>()) // 匿名对象
    {
        _listensocket->BuildListenSocket(_port);
    }

    void InitServer()
    {
        for (int i = 0; i < gnum; ++i)
        {
            fd_events[i].fd = gdefaultfd;
            fd_events[i].events = 0;
            fd_events[i].revents = 0;
        }
        fd_events[0].fd = _listensocket->Sockfd(); // 默认直接添加listen socket
        fd_events[0].events = POLLIN;
    }

    void Loop()
    {
        int timeout = -1;
        while (true)
        {
            int n = ::poll(fd_events, gnum, timeout);
            if (n > 0)
            {
                LOG(INFO, "haved event ready, n : %d\n", n); // 如果事件就绪，但是不处理，poll会一直通知我，直到我处理了！
                HandlerEvent();
                PrintDebug();
            }
            else if (n == 0)
                LOG(DEBUG, "time out\n");
            else
                LOG(ERROR, "select error\n");
        }
    }

    void HandlerEvent() // 分为IO事件或者是listen事件
    {
        for (int i = 0; i < gnum; ++i)
        {
            if (fd_events[i].fd == gdefaultfd)
                continue;

            // 判断是否就绪
            if (fd_events[i].revents & POLLIN)
            {
                if (_listensocket->Sockfd() == fd_events[i].fd)
                    Accepter();
                else
                    HandlerIO(i);
            }
        }
    }

    void Accepter()
    {
        InetAddr addr;
        int sockfd = _listensocket->Accepter(&addr);
        if (sockfd > 0)
        {
            LOG(DEBUG, "get a new link, client info %s:%d\n", addr.Ip().c_str(), addr.Port());

            bool flag = false;
            for (int pos = 0; pos < gnum; ++pos)
            {
                if (fd_events[pos].fd == gdefaultfd)
                {
                    fd_events[pos].fd = sockfd;
                    fd_events[pos].events = POLLIN;
                    flag = true;
                    LOG(INFO, "add %d to fd_array success!\n", sockfd);
                    break;
                }
            }
            if (!flag)
            {
                LOG(WARNING, "Server Is Full!\n");
                ::close(sockfd);
            }
        }
    }

    void HandlerIO(int i)
    {
        char buffer[1024];
        ssize_t n = ::recv(fd_events[i].fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client say# " << buffer << std::endl;
            std::string content = "<html><body><h1>Hello lazy</h1></body></html>";
            std::string echo_str = "HTTP/1.0 200 OK\r\n";
            echo_str += "Content-Type: text/html\r\n";
            echo_str += "Content-Length: " + std::to_string(content.size()) + "\r\n\r\n";
            echo_str += content;
            // echo_str += buffer;
            ::send(fd_events[i].fd, echo_str.c_str(), echo_str.size(), 0); // 临时方案
        }
        else if (n == 0)
        {
            LOG(INFO, "client quit...\n");
            // 关闭fd
            ::close(fd_events[i].fd);
            fd_events[i].fd = gdefaultfd;
            fd_events[i].events = 0;
            fd_events[i].revents = 0;
        }
        else
        {
            LOG(INFO, "client quit...\n");
            // 关闭fd
            ::close(fd_events[i].fd);
            fd_events[i].fd = gdefaultfd;
            fd_events[i].events = 0;
            fd_events[i].revents = 0;
        }
    }

    void PrintDebug()
    {
        std::cout << "fd list: ";
        for (int i = 0; i < gnum; i++)
        {
            if (fd_events[i].fd == gdefaultfd)
                continue;
            std::cout << fd_events[i].fd << " ";
        }
        std::cout << "\n";
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensocket;

    struct pollfd fd_events[gnum];
};